#include "main.h"


C_apiCommunicate::C_apiCommunicate(/* args */)
{
    orderBild = wait;
}

C_apiCommunicate::~C_apiCommunicate()
{

}

void C_apiCommunicate::startLoop(void)
{
    thread1 = std::thread(&C_apiCommunicate::mainLoop, this); // 只能这么写，不这么写会报错
}

// 参考 https://blog.csdn.net/u022812849/article/details/109670281
void C_apiCommunicate::mainLoop(void)
{
    sleep(0.5);
    spdlog::info("C_apiCommunicate wait message");

    // create socket
	int clientfd = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == clientfd) {
        spdlog::info("C_apiCommunicate create socket error");
		return;
	}
	
	// connect server 
	struct sockaddr_in serveraddr;
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_addr.s_addr = inet_addr("192.168.1.196");;
    serveraddr.sin_port = htons(3000);
	
	if(-1 == connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) {
		printf("connect error");
		return;
	}else{
        printf("connect ok\r\n");
    }

	int ret = 0;
    char recvBuf[32] = {0};

	while(1)
    {
        // receive data
        ret = recv(clientfd, recvBuf, 32, 0);
        if (ret > 0) {
            printf("receive data from server: %s", recvBuf);
            setDoSomething(recvBuf);
        } else {
            printf("receive data error: %s", recvBuf);
        }
        
        // send data
        ret = send(clientfd, "receive ok", strlen("receive ok"), 0);
        if (ret != strlen("receive ok")){
            printf("send data error");
            return;
        }
    }

	// close socket
	close(clientfd);

    return;
}

const char order_startBulidMap[] = {"bulidMap"};
void C_apiCommunicate::setDoSomething(char *recvBuf)
{
    int flag = 0;
    int recv = strcmp(recvBuf, order_startBulidMap);
    if(recv == 0) {
       spdlog::info("C_apiCommunicate bulidMap start"); 
       orderBild = start;
    }
    memset(recvBuf,0,32);
}

int C_apiCommunicate::getOrderBuild(void)
{
    return orderBild;
}


void C_apiCommunicate:: taskLoop_bulidMap(void)
{
    // init

}

void C_apiCommunicate:: taskStart_bulidMap(void)
{
    // init

    // loop
    while(1){

    }
}

